package cn.ytr.crm.service.impl;

import cn.ytr.crm.domain.Employee;
import cn.ytr.crm.mapper.EmployeeMapper;
import cn.ytr.crm.query.PageResult;
import cn.ytr.crm.query.QueryObject;
import cn.ytr.crm.service.IEmployeeService;
import cn.ytr.crm.util.UserContext;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private EhCacheManager ehCacheManager;

    /**
     * 保存或编辑员工
     */
    @Override
    public void saveOrUpate(Employee employee, Long[] roleIds) {

        //密码进行加密
        if (employee.getPassword() != null) {
            Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
            employee.setPassword(md5Hash.toString());
        }

        //判断 是否编辑 员工
        if (employee.getId() != null) { //编辑员工
            employeeMapper.updateByPrimaryKey(employee);
            //维护 员工与角色中间表，先把原关系删了，再新增关系
            employeeMapper.deleteRelation(employee.getId());
            if (roleIds != null && roleIds.length > 0) {
                for (Long roleId : roleIds) {
                    employeeMapper.insertRelation(employee.getId(), roleId);
                }
            }

            //清空所有人的缓存
            ehCacheManager.getCacheManager().clearAll();

        } else {    //新增员工
            employeeMapper.insert(employee);
            //维护 员工与角色中间表
            if (roleIds != null && roleIds.length > 0) {
                for (Long roleId : roleIds) {
                    employeeMapper.insertRelation(employee.getId(), roleId);
                }
            }
        }
    }

    /**
     * 删除某员工
     */
    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
        //维护 员工与角色中间表，把关系删了
        employeeMapper.deleteRelation(id);
    }

    /**
     * 获取某员工
     */
    @Override
    @Transactional(readOnly = true)
    public Employee get(Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        return employee;
    }

    /**
     * 获取所有员工
     */
    @Override
    @Transactional(readOnly = true)
    public List<Employee> listAll() {
        List<Employee> list = employeeMapper.selectAll();
        return list;
    }

    /**
     * 高级查询所有员工
     */
    @Override
    @Transactional(readOnly = true)
    public PageResult query(QueryObject qo) {
        Integer count = employeeMapper.selectForCount(qo);
        if (count < 1 || count == null) {
            return new PageResult(qo.getPageSize());
        } else {
            List<Employee> list = employeeMapper.selectForList(qo);
            return new PageResult(qo.getCurrentPage(), count, list, qo.getPageSize());
        }
    }

    /**
     * 员工登录功能
     */
    @Override
    @Transactional(readOnly = true)
    public void login(String name, String password, HttpSession session) {
        Employee employee = employeeMapper.selectByInfo(name, password);
        if (employee == null) {
            throw new RuntimeException("用户名和密码不匹配！");
        } else {
            session.setAttribute("EMPLOYEE_IN_SESSION", employee);
        }
    }

    /**
     * 通过名字和密码获取员工信息
     */
    @Override
    @Transactional(readOnly = true)
    public Employee checkByNameAndPassword(String name, String password) {
        return employeeMapper.selectByInfo(name, password);
    }

    /**
     * 通过 ID 修改员工个人密码
     */
    @Override
    public void editPassword(Long id, String newPassword) {
        employeeMapper.editPasswordById(id, newPassword);

    }

    /**
     * 检测员工用户名是否可用，不重复就返回 true
     */
    @Override
    public boolean checkName(String name) {
        Employee employee = employeeMapper.selectByName(name);
        return employee==null;
    }

    /**
     * 刷新员工登录
     */
    @Override
    public void refreshLogin(Long id) {
        //当前主体
        Subject subject = SecurityUtils.getSubject();
        //员工信息
        Employee employee = UserContext.getCurrentUserByShiro();
        //注销登录然后给自动登录
        subject.logout();
        UsernamePasswordToken token = new UsernamePasswordToken(employee.getName(), employee.getPassword());
        subject.login(token);
    }

    /**
     * 处理 批量删除员工
     */
    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDeleteByIds(ids);
    }

    /**
     * 处理 升级员工为超级管理员
     */
    @Override
    public void upAdmin(Employee employee) {
        employeeMapper.updateByPrimaryKey(employee);
        //清空所有人的缓存
        ehCacheManager.getCacheManager().clearAll();
    }

    /**
     * 处理 导出员工 excel 表
     */
    public Workbook exportXls() throws Exception {
        //创建工作簿
        Workbook wb = new HSSFWorkbook();
        //创建一页纸
        Sheet sheet = wb.createSheet("员工信息表");

        //查询员工数据
        List<Employee> employees = employeeMapper.selectAll();

        //创建行
        //创建列标题
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //具体行数据
        for (int i = 0; i < employees.size(); i++) {
            //创建行
            row = sheet.createRow(i+1);
            Employee employee = employees.get(i);
            //创建单元格，并且赋值
            if (employee.getName() != null) {
                row.createCell(0).setCellValue(employee.getName());
            }
            if (employee.getEmail() != null) {
                row.createCell(1).setCellValue(employee.getEmail());
            }
            if (employee.getAge() != null) {
                row.createCell(2).setCellValue(employee.getAge());
            }
        }

        return wb;
    }

    /**
     * 处理 导入员工 excel 表
     */
    public void importXls(MultipartFile file) throws IOException {
        //读取工作簿
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读一张纸
        Sheet sheet = wb.getSheetAt(0);
        //获取总行数
        int lastRowNum = sheet.getLastRowNum();
        //标题不处理，从1开始
        for (int i = 1; i <= lastRowNum; i++) {
            //读取行
            Row row = sheet.getRow(i);
            //创建员工，设置员工里属性的值
            Employee employee = new Employee();
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());

            //年龄单元格有可能是文本或数字，要进行判断选择合适的格式
            Cell ageCell = row.getCell(2);
            Integer age = null;
            switch (ageCell.getCellType()) {
                case STRING:
                    //作为文本类型的单元格来读取
                    age = Integer.valueOf(ageCell.getStringCellValue());
                    break;
                case NUMERIC:
                    //作为数字类型的单元格来读取
                    age = (int) ageCell.getNumericCellValue();
                    break;
            }

            //设置密码
            employee.setPassword("1");

            //保存员工
            this.saveOrUpate(employee, null);
        }
    }

    /**
     * 通过角色编号查询员工
     */
    public List<Employee> selectByRoleSn(String... snArr) {
        return employeeMapper.selectByRoleSn(snArr);
    }

}

















































